package com.manor.main.utils;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.allenliu.versionchecklib.callback.APKDownloadListener;
import com.allenliu.versionchecklib.callback.OnCancelListener;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;

import java.io.File;

import androidx.annotation.NonNull;
import com.manor.common.utils.ActivityManager;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.main.R;

/**

 * @version 1.0

 * @date 2020/4/21  10:53
 */
public class UpdateUtil {

    public static UpdateUtil instance = null;

    private AsyncTask mAsyncTask;//<Object, Void, File>

    static {
        if (instance == null) {
            instance = new UpdateUtil();
        }
    }

    private UpdateUtil() {
    }

    public void initDownload(Context mContext, String title, String content, String apkUrl, int versionCode,
                             boolean isForce) {
        initDownload(mContext, title, content, apkUrl, versionCode, isForce, "1", "");
    }

    public void initDownload(Context mContext, String title, String content, String apkUrl, int versionCode,
                             boolean isForce, String upType, String patchUrl) {
        //初始化下载
        if (StringUtil.isEmpty(apkUrl) && StringUtil.isEmpty(patchUrl)) {
            return;
        }
        //1全量更新 2增量更新 3新增补丁
        String downUrl = apkUrl;

        DownloadBuilder builder = AllenVersionChecker.getInstance()
                .downloadOnly(crateUIData(title, content, downUrl));

        if (isForce) {
            builder.setForceUpdateListener(new ForceUpdateListener() {
                @Override
                public void onShouldForceUpdate() {
                    ActivityManager.getInstance().finishAllActivity();
                }
            });
        }

//        暂去除增量更新

        //额外校验，传入code大于本地code，重新下载
        builder.setNewestVersionCode(versionCode);
        //强制重新下载apk（无论本地是否缓存）
        builder.setForceRedownload(false);
        //显示下载中对话框
        builder.setShowDownloadingDialog(isForce);
        //显示下载通知栏
        builder.setShowNotification(true);
        //显示下载失败对话框
        builder.setShowDownloadFailDialog(true);
        //更新界面
        builder.setCustomVersionDialogListener(createCustomDialogTwo(!isForce));
        builder.setCustomDownloadingDialogListener(createCustomDownload());
        builder.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel() {
                ToastUtil.show("取消安装");
            }
        });

        builder.setApkDownloadListener(new APKDownloadListener() {
            @Override
            public void onDownloading(int progress) {

            }

            @Override
            public void onDownloadSuccess(File file) {
            }

            @Override
            public void onDownloadFail() {
            }
        });
        builder.executeMission(mContext);

    }







    private UIData crateUIData(String title, String content, String apkUrl) {
        UIData uiData = UIData.create();
        uiData.setTitle(title);
        uiData.setDownloadUrl(apkUrl);
        uiData.setContent(content);
        return uiData;
    }

    private CustomVersionDialogListener createCustomDialogTwo(boolean isCanOut) {
        return new CustomVersionDialogListener() {
            @Override
            public Dialog getCustomVersionDialog(Context context, UIData versionBundle) {
                BaseUpdateDialog baseDialog = new BaseUpdateDialog(context, R.style.BaseUpdateDialog,
                        R.layout.dialog_update_layout);
                ((TextView) baseDialog.findViewById(R.id.tv_msg)).setText(versionBundle.getContent());
                ((TextView) baseDialog.findViewById(R.id.tv_title)).setText(versionBundle.getTitle());
                baseDialog.setCanceledOnTouchOutside(isCanOut);
                return baseDialog;
            }
        };
    }

    private CustomDownloadingDialogListener createCustomDownload() {
        return new CustomDownloadingDialogListener() {
            @Override
            public Dialog getCustomDownloadingDialog(Context context, int progress, UIData versionBundle) {
                BaseUpdateDialog baseDialog = new BaseUpdateDialog(context, R.style.BaseUpdateDialog,
                        R.layout.dialog_update_layout);
                baseDialog.findViewById(R.id.versionchecklib_version_dialog_commit).setVisibility(View.GONE);
                baseDialog.findViewById(R.id.llPB).setVisibility(View.VISIBLE);
                ((TextView) baseDialog.findViewById(R.id.tv_msg)).setText(versionBundle.getContent());
                ((TextView) baseDialog.findViewById(R.id.tv_title)).setText(versionBundle.getTitle());
                baseDialog.setCanceledOnTouchOutside(false);
                return baseDialog;
            }

            @Override
            public void updateUI(Dialog dialog, int progress, UIData versionBundle) {
                TextView tvProgress = dialog.findViewById(R.id.tv_progress);
                ProgressBar pbProgress = dialog.findViewById(R.id.pb_progress);
                tvProgress.setText(progress+"%");
                pbProgress.setMax(100);
                pbProgress.setProgress(progress);
            }

        };
    }

    class BaseUpdateDialog extends Dialog {
        public BaseUpdateDialog(@NonNull Context context, int theme, int res) {
            super(context, theme);
            setContentView(res);
            setCanceledOnTouchOutside(false);
        }
    }


}
